package com.cloud.bssp.java8.stream;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 * @description： 挑选手机
 * @author：weirx
 * @date：2021/10/15 16:02
 * @version：3.0
 */
public class ChoicePhone {

    public static void main(String[] args) {
        List<Phone> list = new ArrayList<>();
        list.add(new Phone("苹果", "黑色"));
        list.add(new Phone("华为", "黑色"));
        List<Phone> blackPhones = phoneFilter(list, ChoicePhone::isBlack);
        System.out.println(blackPhones.toString());
        List<Phone> huaweiPhones = phoneFilter(list, (Phone p) -> "华为".equals(p.brand));
        System.out.println(huaweiPhones.toString());
    }

    @Data
    static class Phone {
        private String brand;

        public Phone(String brand, String color) {
            this.brand = brand;
            this.color = color;
        }

        private String color;
    }

    /**
     * 筛选华为方法
     */
    public static boolean isHuawei(Phone phone) {
        return "华为".equals(phone.getBrand());
    }

    /**
     * 筛选黑色方法
     */
    public static boolean isBlack(Phone phone) {
        return "黑色".equals(phone.getColor());
    }

    /**
     * 手机过滤方法，参数是手机list和Predicate<T>函数
     */
    public static<T> List<T> phoneFilter(List<T> list, Predicate<T> p) {
        List<T> results = new ArrayList<>();
        for (T t : list) {
            if (p.test(t)) {
                results.add(t);
            }
        }
        return results;
    }
}
